package com.bawei.movie

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.movie.adapter.MoviePager2Adapter
import com.bawei.movie.adapter.MoviePagerAdapter
import com.bawei.movie.databinding.FragmentMovieBinding
import com.bawei.movie.entity.MovieTabEntity
import com.bawei.movie.viewmodel.MovieViewModel
import com.bumptech.glide.Glide
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MovieFragment : BaseMviFragment<FragmentMovieBinding>() {

    private val mViewModel: MovieViewModel by activityViewModels()

    private val searchHints = mutableListOf("热门视频", "头条视频", "星际迷航", "神枪手")
    private var menuTabs = mutableListOf<MovieTabEntity>()
    private var tabs = mutableListOf<MovieTabEntity>()
    private val fragments = mutableListOf<MovieListFragment>()
    private lateinit var pageAdapter: MoviePagerAdapter
    private lateinit var pageAdapter2: MoviePager2Adapter
    private lateinit var mXPopupBuilder: XPopup.Builder
    private var mPid: Int = 1

    override fun getLayoutId(): Int = R.layout.fragment_movie

    override fun initViews() {
        mDataBinding.tbvSearch.setDatas(searchHints)
        //初始化XPopup
        mXPopupBuilder = XPopup.Builder(requireContext()).atView(mDataBinding.cltFilter)
        //筛选按钮点击事件
        mDataBinding.tvFilter.setOnClickListener {
            showMovieFilter()
        }
        //页面改变回调事件
        mDataBinding.vpVideo.registerOnPageChangeCallback(object : OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                //更新Fragment的数据
                fragments[position].updateData(tabs[position].id)
            }

            override fun onPageScrollStateChanged(state: Int) {
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    Glide.with(this@MovieFragment).resumeRequests() //恢复图片加载
                } else {
                    Glide.with(this@MovieFragment).pauseRequests() //暂停图片加载
                }
            }
        })
        //使用ViewPager2实现，重点是内部采用RecyclerView的实现方式，可以利用RecyclerView的四级缓存，进而达到Fragment的复用
        pageAdapter2 = MoviePager2Adapter(fragments, this@MovieFragment.childFragmentManager, lifecycle)
        mDataBinding.vpVideo.adapter = pageAdapter2

        //TabLayout与ViewPager2关联
        TabLayoutMediator(mDataBinding.tabTypeLayout,  mDataBinding.vpVideo){ tab, position ->
            tab.text = tabs[position].typename
        }.attach()

    }

    private fun showMovieFilter(){
        if(menuTabs.isNotEmpty()){
            var titleArray = mutableListOf<String>()
            menuTabs.forEach {
                titleArray.add(it.typename)
            }
            mXPopupBuilder.asAttachList(titleArray.toTypedArray(), null) { position: Int, _: String ->
                mPid = menuTabs[position].id
                //加载二级视频分类Tab
                lifecycleScope.launch {
                    mViewModel.channel.send(MovieViewIntent.LoadMovieTypeById(mPid))
                }
            }.show()
        }
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(MovieViewIntent.LoadMovieType)
        mViewModel.channel.send(MovieViewIntent.LoadMovieTypeById(mPid))
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is MovieUiState.LoadMovieTypeSuccess -> initPopupWindow(it.list)
                is MovieUiState.LoadMovieTypeByIdSuccess -> initFragments(it.list)
                is MovieUiState.LoadMovieTypeFail -> showToastMessage(it.msg)
                is MovieUiState.LoadMovieTypeByIdFail ->  loadTabsFail()
                else -> {}
            }
        }
    }

    private fun initPopupWindow(list: List<MovieTabEntity>){
        if (list.isNotEmpty()){
            menuTabs.clear()
            menuTabs.addAll(list)
        }
    }

    private fun loadTabsFail(){
        tabs.clear()
        fragments.clear()
        //推荐Tab实体
        tabs.add(MovieTabEntity("", 0,-1, 0, "", "推荐"))
        //设置Tabs
        tabs.forEach {
            mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
        }
        fragments.add(MovieListFragment.newInstance(-1))
//        pageAdapter.notifyDataSetChanged()
//        pageAdapter2 = MoviePager2Adapter(fragments, this@MovieFragment.requireActivity())
//        mDataBinding.vpVideo.adapter = pageAdapter2
        pageAdapter2.notifyDataSetChanged()

    }

    private fun initFragments(list: List<MovieTabEntity>){
        if(list.isNotEmpty()){
            tabs.clear()
            fragments.clear()
            //推荐Tab实体
            tabs.add(MovieTabEntity("", 0,-1, 0, "", "推荐"))
            fragments.add(MovieListFragment.newInstance(-1))
            //添加分类Fragment
            list.forEach { item ->
                tabs.add(item)
                fragments.add(MovieListFragment.newInstance(item.id))
            }
            //设置Tab数据
            tabs.forEach {
                mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
            }
//            pageAdapter.notifyDataSetChanged()
//            pageAdapter2 = MoviePager2Adapter(fragments, this@MovieFragment.requireActivity())
//            mDataBinding.vpVideo.adapter = pageAdapter2
            pageAdapter2.notifyDataSetChanged()
        }
    }


}